package io.gitee.zhucan123.core.infrastructure.util;

import java.util.*;
import java.util.function.Function;

/**
 * @author guodu
 * @date 2019/9/6
 */
public class StringUtils {

  /**
   *
   * @param str key1=value1,key2=value2 的形式
   * @param keyValueDelimiter key和value之间的分隔符，str中的例子的keyValueDelimiter is '='
   * @param delimiter key value pair 之间的分隔符，str中的例子中为 ','
   * @param keyConverter
   * @param valueConverter
   * @param <KEY>
   * @param <VALUE>
   * @return
   */
  public static <KEY,VALUE> Map<KEY, VALUE> strToMap(
      String str, String keyValueDelimiter, String delimiter,
      Function<String, KEY> keyConverter, Function<String, VALUE> valueConverter) {
    Map<KEY, VALUE> map = new HashMap<>();
    String nextDelimiter = keyValueDelimiter;
    String key = null;
    int i = 0;
    while(i < str.length()) {
      int index = str.indexOf(nextDelimiter, i);
      String token;
      if(index < 0) {
        index = str.length();
        token = str.substring(i);
      } else {
        token = str.substring(i, index);
      }
      if(key == null) {
        key = token;
        nextDelimiter = delimiter;
      } else {
        nextDelimiter = keyValueDelimiter;
        map.put(keyConverter.apply(key), valueConverter.apply(token));
        key = null;
      }
      i = index + 1;
    }
    return map;
  }

  public static <T> String join(CharSequence delimiter, Collection<T> col, Function<T, String> stringer) {
    List<String> strList = new ArrayList<>(col.size());
    for (T ele : col) {
      strList.add(stringer.apply(ele));
    }
    return String.join(delimiter, strList);
  }

}
